// src/utils/websocket.js
export default {
  socket: null,

  // 连接 WebSocket
  connectWebSocket(url, onOpenCallback, onMessageCallback, onErrorCallback, onCloseCallback) {
    // 动态判断环境（开发环境可能需代理）
    const isDev = process.env.NODE_ENV === 'development';
    const wsUrl = isDev ? 'ws://localhost:8080/ws/message' : url;

    this.socket = uni.connectSocket({
      url: wsUrl,
      success: () => {
        console.log('WebSocket 连接初始化');
      }
    });

    // 监听事件
    this.socket.onOpen(() => {
      console.log('WebSocket 连接成功');
      if (onOpenCallback) {
        onOpenCallback();
      }
    });

    this.socket.onMessage((res) => {
      const message = res.data;
      if (onMessageCallback) {
        onMessageCallback(message);
      }
      console.log('收到消息:', message);
    });

    this.socket.onError((err) => {
      console.error('WebSocket 错误:', err);
      if (onErrorCallback) {
        onErrorCallback(err);
      }
    });

    this.socket.onClose(() => {
      console.log('WebSocket 连接关闭');
      if (onCloseCallback) {
        onCloseCallback();
      }
    });
  },

  // 发送消息
  sendMessage(data) {
    if (this.socket && this.socket.send) {
      this.socket.send({
        data: JSON.stringify(data)
      });
    }
  },

  // 关闭 WebSocket 连接
  closeConnection() {
    if (this.socket) {
      this.socket.close();
    }
  }
};
